local core        = require("apisix.core")
local api_request = require("apisix.plugins.api-request")
local ngx         = ngx


local plugin_name = "api-info"

local schema = {
    type = "object",
    properties = {
        level = { type = "string", default = "notice" },
        debug = { type = "boolean", default = true },
    }
}

local _M = {
    version  = 0.1,
    priority = 1000,  -- 高优先级确保先执行
    name     = plugin_name,
    schema   = schema,
}

-- 日志定义
local L = {
    prefix = "api-info ===> ",
    level = "notice",
    debug = true,
}

-- 日志控制
function L.log(...)
    if L.debug then
        core.log.new(L.prefix)[L.level](...)
    end
end

-- 获取完整请求信息
function _M.access(conf, ctx)
    L.level = conf.level
    L.debug = conf.debug

    -- 收集请求数据
    local json_body, err = core.json.encode({
        headers = api_request.get_header_params(ctx),
        query   = api_request.get_query_params(ctx),
        body    = api_request.get_body_all_params(ctx),
        method  = core.request.get_method(),
        scheme  = core.request.get_scheme(),
        host    = core.request.get_host(),
        uri     = ngx.var.uri,
        time    = ngx.localtime()
    })
    if not json_body then
        L.log("error", "JSON encode failed: ", err)
        json_body = '{ "error": "Failed to encode response" }'
    end

    -- 发送响应并终止请求
    core.response.set_header("Content-Type", "application/json; charset=utf-8")
    return core.response.exit(200, json_body)
end

return _M